#!/usr/bin/env python
# encoding: utf-8
"""
views.py
@author Andrey Pavlenko
"""
import os

from google.appengine.api import users

from google.appengine.ext import db
from google.appengine.ext.db import djangoforms

import django
from django import http
from django import shortcuts

from model import Post

class PostForm(djangoforms.ModelForm):
    class Meta:
        model = Post
        exclude = ['comments_count', 'author', 'modify_date']

def respond(request, user, template, params=None):
  """Helper to render a response, passing standard stuff to the response.

  Args:
    request: The request object.
    user: The User object representing the current user; or None if nobody
      is logged in.
    template: The template name; '.html' is appended automatically.
    params: A dict giving the template parameters; modified in-place.

  Returns:
    Whatever render_to_response(template, params) returns.

  Raises:
    Whatever render_to_response(template, params) raises.
  """
  if params is None:
    params = {}
  if user:
    params['user'] = user
    params['sign_out'] = users.create_logout_url('/')
    params['is_admin'] = (users.is_current_user_admin() and
                          'Dev' in os.getenv('SERVER_SOFTWARE'))
  else:
    params['sign_in'] = users.create_login_url(request.path)
  if not template.endswith('.html'):
    template += '.html'
  return shortcuts.render_to_response(template, params)


def index(request):
  """Request / -- show first page with 5 posts."""
  user = users.get_current_user()
  posts = db.GqlQuery('SELECT * FROM Post ORDER BY public_date DESC')
  return respond(request, user, 'list', {'posts': posts})


def edit(request, post_id):
    """Create or edit a post.  GET shows a blank form, POST processes it."""
    user = users.get_current_user()
    if user is None:
        return http.HttpResponseForbidden('You must be signed in to add or edit a post')
    if not users.is_current_user_admin():
        return http.HttpResponseForbidden('Only admin may edit post')
    post = None
    if post_id:
        post = Post.get(db.Key.from_path(Post.kind(), int(post_id)))
        if post is None:
            return http.HttpResponseNotFound('No post exists with that key (%r)' % post_id)
    form = PostForm(data=request.POST or None, instance=post)
    if not request.POST:
        return respond(request, user, 'post', {'form': form, 'post': post})
    errors = form.errors
    if not errors:
        try:
            post = form.save(commit=False)
        except ValueError, err:
            errors['__all__'] = unicode(err)
    if errors:
        return respond(request, user, 'post', {'form': form, 'post':post})
    if not post.author:
        post.author = user
    post.put()
    return http.HttpResponseRedirect('/')


def new(request):
    """Create a post.  GET shows a blank form, POST processes it."""
    return edit(request, None)
